package com.company.restaurant.service.handler;

import com.company.restaurant.dto.BaseMessage;
import com.company.restaurant.dto.MessageIds;
import com.company.restaurant.dto.MessageWrapper;
import com.company.restaurant.dto.Protocol;
import com.company.restaurant.service.convertor.ConverterManager;
import com.company.restaurant.service.session.SessionManager;
import com.company.restaurant.service.session.TcpClientSession;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Description of class.
 * Created 3/26/14 5:31 PM
 *
 * @author andrey.rodin@playtech.com
 */

public class MessageHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        TcpClientSession clientSession = new TcpClientSession();
        clientSession.setChannel(ctx);
        SessionManager.addNewSession(clientSession);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
        MessageWrapper messageWrapper = (MessageWrapper) msg;
        BaseMessage message = ConverterManager.processConverter(MessageIds.getByCode(messageWrapper.getCode()), messageWrapper.getMessage());
        TcpClientSession session = SessionManager.getSession(ctx);

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        SessionManager.removeSession(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
